package com.cz.shopping.manager.helper;

import com.cz.shopping.model.entity.system.SysMenu;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description <>
 * @author: zhouchaoyu
 * @Date: 2023-11-08
 */
public class MenuHelper {
    private static final long ROOT_ID = 0;

    /**
     * 使用递归方法建菜单
     *
     * @param sysMenuList
     * @return
     */
    public static List<SysMenu> buildTree(List<SysMenu> sysMenuList) {
        List<SysMenu> trees = sysMenuList.stream()
                .filter(sysMenu -> {
                    return sysMenu.getParentId().longValue() == ROOT_ID;
                })
                .sorted((m1, m2) -> {
                    return ((m1.getSortValue() == null ? 0 : m1.getSortValue()) - (m2.getSortValue() == null ? 0 : m2.getSortValue()));
                })
                .map(rootNode -> {
                            rootNode.setChildren(findChildren(rootNode, sysMenuList));
                            return rootNode;
                        }
                ).collect(Collectors.toList());

        return trees;
    }

    /**
     * 递归查找子节点
     *
     * @param treeNodes
     * @return
     */
    public static List<SysMenu> findChildren(SysMenu sysMenu, List<SysMenu> treeNodes) {
        List<SysMenu> childrenMenu = treeNodes.stream()
                .filter(node -> node.getParentId().longValue() == sysMenu.getId().longValue())
                .sorted(Comparator.comparingInt(m -> (m.getSortValue() == null ? 0 : m.getSortValue())))
                .map(menu -> {
                    menu.setChildren(findChildren(menu, treeNodes));
                    return menu;
                }).collect(Collectors.toList());
        return childrenMenu;
    }
}
